//
//  YH_ChangePasswordViewController.m
//  YinHang
//
//  Created by apple on 14-9-18.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_ChangePasswordViewController.h"

@interface YH_ChangePasswordViewController ()<UITextFieldDelegate,ASIHTTPRequestDelegate>{
    ASIFormDataRequest *changePWDrequest;
}

@end

@implementation YH_ChangePasswordViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title=@"密码修改";
    //设置返回按钮
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    //设置修改按钮
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-40, 5, 40, 30)];
    
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn setTintColor:[UIColor whiteColor]];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIImage *postBtn_bgImg = [UIImage imageNamed:@"postbtn_bg"];
    [rightBtn setBackgroundImage:[postBtn_bgImg stretchableImageWithLeftCapWidth:postBtn_bgImg.size.width*0.5f topCapHeight:postBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];

    [rightBtn addTarget:self action:@selector(savePassword) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    if (ios7) {
        self.navigationItem.rightBarButtonItems = @[negativeSpacer,rightBarButtonItem];
    }else{
        self.navigationItem.rightBarButtonItems = @[rightBarButtonItem];
    }
    
    
    
    //修改密码键盘类型
    _oldPassword.keyboardType=_Password.keyboardType=_PasswordAgain.keyboardType=UIKeyboardTypeAlphabet;
    _oldPassword.delegate=_Password.delegate=_PasswordAgain.delegate=self;
    _oldPassword.secureTextEntry = YES; //密码
    
      _oldPassword.clearButtonMode =_Password.clearButtonMode=_PasswordAgain.clearButtonMode= UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
}
-(void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden=YES;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [_oldPassword resignFirstResponder];
    [_Password resignFirstResponder];
    [_PasswordAgain resignFirstResponder];



}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{

  
    [textField resignFirstResponder];
    return YES;
}

// 密码输入限制（数字字母下划线） <12位
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _Password || textField==_PasswordAgain) {
        // return NO to not change text
        if(strlen([textField.text UTF8String]) >= 12 && range.length != 1)
            return NO;
    }
    
    return YES;
}



// 返回
- (void)back {
    
    [self.navigationController popViewControllerAnimated:YES];
}



//保存密码
-(void)savePassword{
    
    if (![_oldPassword.text isEqualToString:UPWD_OLD]) {
        [SVProgressHUD showErrorWithStatus:@"原密码不正确"];
    }else{
    if ([_oldPassword.text isEqual:@""]) {
         [SVProgressHUD showErrorWithStatus:@"请输入原密码"];
    }
    // 密码输入限制（数字字母下划线） >6位
 
        else if(strlen([_PasswordAgain.text UTF8String]) <6 || strlen([_Password.text UTF8String]) <6)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wrong password" message:@"Password can not less than 6 character" delegate:self cancelButtonTitle:@"Go on Input" otherButtonTitles:nil];
            [alert show];
            
        }
        else if (![_Password.text isEqualToString:_PasswordAgain.text]){
            [SVProgressHUD showErrorWithStatus:@"和所填密码不符 请再次确认！"];
        }
        else if ([_Password.text isEqualToString:_oldPassword.text]){
        
        [SVProgressHUD showErrorWithStatus:@"新旧密码相同 请再次确认！"];
        }
        else{
            [self touchesBegan:nil withEvent:nil];
            // 检查网络
            if (![Constants isExistenceNetwork]) {
            
            } else {
                changePWDrequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
                changePWDrequest.requestMethod = @"POST";
                // 设置超时时间
                changePWDrequest.timeOutSeconds = 30;
                changePWDrequest.delegate = self;
                // 设置参数
                //新密码
                NSString *newPassword = _Password.text;
                NSString *action = @"resetpwd";
                NSLog(@"%@",UNAME);
                NSDictionary *paramsDict =  @{@"uid":UNAME, @"newpwd": [newPassword md5]};
                NSString *paramsStr = [NSString JSONString:paramsDict];
                NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
                
                NSData *paramsData = [result toGBKEncodingData];
                changePWDrequest.postBody = [paramsData mutableCopy];
                
                [changePWDrequest startAsynchronous];
            }
        }
    }
}
#pragma mark - ASIHTTPRequestDelegate Method

- (void)requestFinished:(ASIHTTPRequest *)request {
    //NSLog(@"%@",request.responseString);
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            
            UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(100, 300, 120, 30)];
            
            
            label.layer.shadowColor = [UIColor blackColor].CGColor;
            label.layer.cornerRadius=5.0;
            label.layer.shadowOpacity = .7;
            label.layer.shadowRadius = 3.0;
            label.layer.shadowOffset = CGSizeMake(0, 0);
            
            label.text=@"密码已生效";
            label.textAlignment=NSTextAlignmentCenter;
            label.textColor=[UIColor whiteColor];
            label.font=[UIFont  boldSystemFontOfSize:14];
            label.backgroundColor=[UIColor blackColor];
            [self.view addSubview:label];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.3* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                label.alpha=0;
                [self.navigationController popViewControllerAnimated:YES];
            });
            
            NSLog(@"保存成功");
            //更新密码 用于修改
            [[NSUserDefaults standardUserDefaults] setObject:_Password.text forKey:@"userpwd"];
            
        } else {
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

-(void)dealloc{
    [changePWDrequest cancel];
}
@end
